package top.fyxxxx.downloader.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SqlUtil {
    public static SQLiteDatabase db;
    public static DbHelper dbHelper;
    private Context context;
    private SqlUtil(Context context) {
        this.context = context;
        dbHelper = new DbHelper(context);
    }

    private static SqlUtil instance;

    public static SqlUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (SqlUtil.class) {
                if (instance == null) instance = new SqlUtil(context);
            }
        }
        return instance;
    }

    /***
     * 插入历史记录
     * @param history 历史记录
     */
    public void insertHistory(History history) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("INSERT INTO history(date,filename, filepath ,url, filesize ,downloadedsize,status ) values(?,?,?,?,?,?,?)",
                new String[]{history.getDate() + "", history.getFileName(), history.getFilePath(),history.getUrl(), history.getFileSize() + "", history.getDownloadedSize() + "", history.getStatus() + ""});
    }

    public void updateHistory(History history) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("UPDATE  history SET date= ? ,filename =? , filepath = ? ,url = ?, filesize =? ,downloadedsize = ?,status =? WHERE filename = ?",
                new String[]{history.getDate() + "", history.getFileName(), history.getFilePath(), history.getUrl(), history.getFileSize() + "", history.getDownloadedSize() + "", history.getStatus() + "", history.getFileName()});
    }

    /***
     * 删除历史记录
     * @param history 以日期为key删除历史记录
     */
    public void deleteHistory(History history) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("DELETE FROM history WHERE filename = ?",
                new String[]{history.getFileName() + ""});
    }

    /***
     * 历史记录查询
     * @return 返回所有历史记录 按日期倒序排序
     */
    public List<History> getAllHistory() {
        db = dbHelper.getWritableDatabase();
        List<History> historys = new ArrayList<History>();
        Cursor cursor = db.rawQuery("SELECT * FROM history ORDER BY date DESC ",
                new String[]{});
        while (cursor.moveToNext()) {
            long date = cursor.getLong(cursor.getColumnIndex("date"));
            String fileName = cursor.getString(cursor.getColumnIndex("filename"));
            String filePath = cursor.getString(cursor.getColumnIndex("filepath"));
            String url=cursor.getString(cursor.getColumnIndex("url"));
            long fileSize = cursor.getLong(cursor.getColumnIndex("filesize"));
            long downloadedSize = cursor.getLong(cursor.getColumnIndex("downloadedsize"));
            int status = cursor.getInt(cursor.getColumnIndex("status"));
            historys.add(new History(fileName, filePath,url, status, date, fileSize, downloadedSize));
        }
        cursor.close();
        return historys;
    }

    /***
     * 历史记录查询
     * @param filename
     * @return 历史记录
     */
    public History getHistory(String filename)
    {
        db = dbHelper.getWritableDatabase();
        History history=null;
        Cursor cursor = db.rawQuery("SELECT * FROM history ORDER BY date DESC ",
                new String[]{});
        while (cursor.moveToNext()) {
            long date = cursor.getLong(cursor.getColumnIndex("date"));
            String fileName = cursor.getString(cursor.getColumnIndex("filename"));
            String filePath = cursor.getString(cursor.getColumnIndex("filepath"));
            String url=cursor.getString(cursor.getColumnIndex("url"));
            long fileSize = cursor.getLong(cursor.getColumnIndex("filesize"));
            long downloadedSize = cursor.getLong(cursor.getColumnIndex("downloadedsize"));
            int status = cursor.getInt(cursor.getColumnIndex("status"));
            history=new History(fileName, filePath,url, status, date, fileSize, downloadedSize);
        }
        cursor.close();
        return history;
    }
    /***
     * 增加树节点
     * @param son
     * @param father
     */
    public void insertTreeNode(String son, String father) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("INSERT INTO tree(son,father) values(?,?)",
                new String[]{son, father});
    }

    /***
     * 更新树节点
     * @param son
     * @param father
     */
    public void updateTreeNode(String son, String father) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("UPDATE  tree SET father=? WHERE son =?",
                new String[]{father, son});
    }

    /***
     * 删除树节点
     * @param son 节点名字
     */
    public void deleteTreeNode(String son) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("DELETE FROM tree WHERE son = ?",
                new String[]{son});
    }

    /***
     * 获取节点父亲
     * @param son 节点
     * @return
     */
    public String getTreeNodeFather(String son) {
        db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM tree WHERE son = ?",
                new String[]{son});
        //存在数据才返回
        if (cursor.moveToFirst()) {
            String father = cursor.getString(cursor.getColumnIndex("father"));
            cursor.close();
            return father;
        }
        cursor.close();
        return null;
    }

    /***
     * 获取节点儿子
     * @param father 父节点
     * @return
     */
    public List<String> getTreeNodeSon(String father) {
        db = dbHelper.getWritableDatabase();
        List<String> sons = new ArrayList<>();
        Cursor cursor = db.rawQuery("SELECT * FROM tree WHERE father = ?",
                new String[]{father});
        //存在数据才返回
        while (cursor.moveToNext()) {
            String son = cursor.getString(cursor.getColumnIndex("father"));
            sons.add(son);
        }
        cursor.close();
        return sons;
    }

    private String getValue(String key, String defaultvalue) {
        String Value = getTreeNodeFather(key);
        if (Value == null) insertTreeNode(key, defaultvalue);
        else return Value;
        return defaultvalue;
    }

    private boolean setValue(String key, String value) {
        if (!getValue(key, "").equals(value)) {
            updateTreeNode(key, value);
            return true;
        }
        return false;
    }

    public int getThreadNum() {
        String key = "ThreadNum";
        int defaultThreadNum = 5;
        return Integer.valueOf(getValue(key, defaultThreadNum + ""));
    }

    public void setThreadNum(int ThreadNum) {
        String key = "ThreadNum";
        if (setValue(key, ThreadNum + "")) {
            //在这里写变更并行任务数后需要调用的方法。
            DownloadManager.getInstance(context).setThreadNum(ThreadNum);
        }
    }

    public String getDownloadPath() {
        String key = "DownloadPath";
        String defaultDownloadPath = "/sdcard/Download";
        return getValue(key, defaultDownloadPath);
    }

    public void setDownloadPath(String DownloadPath) {
        String key = "DownloadPath";
        setValue(key, DownloadPath);
    }
}

